<?php
namespace common\models\user;

use common\models\Common;
use common\models\Functions;
use yii\base\Exception;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserLoginStatistic extends Common
{
    public $endDate = '';

    public static function tableName()
    {
        return '{{%user_login_statistic}}';
    }

    //获取用户
    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
     * 操作列表
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getList($page = 1, $size = 10) {
        try {
            $get = \Yii::$app->request->get();

            $andWhere = $where = [];
            $phone = $get['phone'];
            if (!empty($phone)) {
                $andWhere[] = ["LIKE", "phone", $phone];
            }
            $count = static::getCountByAndWhere($where, $andWhere);
            $offset = ($page - 1) * $size;
            $data = $this->setPageinationAPI($page, $size, $count);

            $order = 'times DESC';
            $list = static::getByAndWhere($where, $andWhere, "*", $order, $offset, $size);


            $result = [];
            foreach ($list as $k => $v) {
                $tmp['id'] = (int) $v['id'];
                $tmp['ip'] = $v['ip'];
                $tmp['times'] = $v['times'];
                $tmp['phone'] = $v['phone'];
                $tmp['status'] = $v['status'];

                $result[] = $tmp;
            }
            $data['data'] = $result;

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public static function record($phone = '') {
        $data['ip'] = Functions::getRemoteIp();

        if (empty($data['ip'])) {
            $data['ip'] = \Yii::$app->request->remoteIP;
        }
        $info = static::getOneByWhere($data);

        if (!empty($info)) {
            $phones = explode(",", $info['phone']);
            if (!in_array($phone, $phones)) {
                $phones[] = $phone;
                $data['phone'] = implode(",", $phones);
            }
            $data['times'] = $info['times'] + 1;

            static::updateData($data, ['id' => $info['id']]);
        } else {
            $data['phone'] = $phone;
            $data['times'] = 1;
            $data['create_time'] = date("Y-m-d H:i:s");
            static::insertData($data);
        }
        return !empty($count);
    }

}
